package com.projectfixit.web;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.projectfixit.dao.AuthDao;
import com.projectfixit.entity.AuthDO;

public class AuthRegister extends HttpServlet {
	private static final long serialVersionUID = -5589398999865825828L;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String repeat = request.getParameter("repeat");
		HttpSession session = request.getSession();

		if (password != null && repeat != null && password.length() > 0 && !password.equalsIgnoreCase(repeat)) {
			session.setAttribute("logsuccessful", "false");
			response.sendRedirect("/register.jsp");
		}

		if (email != null && !email.isEmpty()) {
			AuthDao authDao = new AuthDao();
			AuthDO authdo = authDao.getAuthDO(email);
			if (authdo != null) {
				session.setAttribute("logsuccessful", "false");
				response.sendRedirect("/register.jsp");
			} else {
				try {
					authdo = new AuthDO(email, password);
					authDao.putAuthDO(authdo);
					session.setAttribute("login", "true");
					session.setAttribute("logsuccessful", "true");
					// request.getRequestDispatcher("/WEB-INF/author/report.jsp");
					response.sendRedirect("/report.jsp");
				} catch (NoSuchAlgorithmException e) {
					e.printStackTrace();
					session.setAttribute("logsuccessful", "false");
					response.sendRedirect("/register.jsp");
				}
			}
		}

	}

}
